package com.block.common.service.merchant.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.service.merchant.IMerchantThirdProtocolInfoService;
import com.block.db.entity.MerchantThirdBaseInfo;
import com.block.db.entity.MerchantThirdProtocolInfo;
import com.block.db.mapper.MerchantThirdBaseInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商户的机构基本信息 服务实现类
 * </p>
 *
 * @author
 * @since 2024-01-17
 */
@Service
public class MerchantThirdBaseInfoServiceImpl extends ServiceImpl<MerchantThirdBaseInfoMapper, MerchantThirdBaseInfo> implements IMerchantThirdBaseInfoService {

    @Autowired
    IMerchantThirdProtocolInfoService merchantThirdProtocolInfoService;
    @Autowired
    NotifyExceptionService notifyExceptionService;

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class)
    public boolean saveThirdInfo(ThirdInfoDTO thirdInfoDTO) {

        try {

            String dateInfo = LocalDate.now().toString();
            MerchantThirdBaseInfo thirdBaseInfo = new MerchantThirdBaseInfo();
            thirdBaseInfo.setDateInfo(dateInfo);
            thirdBaseInfo.setInfoId(thirdInfoDTO.getInfoId());
            thirdBaseInfo.setInfoName(thirdInfoDTO.getInfoName());
            thirdBaseInfo.setPushId(thirdInfoDTO.getOrderNo());

            JSONObject infoObject = thirdInfoDTO.getInfoObject();

            thirdBaseInfo.setOutOrderNo(infoObject.getString("orderNo"));
            thirdBaseInfo.setProductId(infoObject.getString("productId"));
            thirdBaseInfo.setProductName(infoObject.getString("productName"));
            thirdBaseInfo.setCompanyName(infoObject.getString("companyName"));
            thirdBaseInfo.setCompanyLogo(infoObject.getString("companyLogo"));
            thirdBaseInfo.setMaxLoanAmount(infoObject.getString("maxLoanAmount"));
            thirdBaseInfo.setMaxLoanRate(infoObject.getString("maxLoanRate"));
            thirdBaseInfo.setMinLoanRate(infoObject.getString("minLoanRate"));
            thirdBaseInfo.setBusinessInfo(infoObject.getString("businessInfo"));

            boolean save = this.save(thirdBaseInfo);
            if (!save) {
                return false;
            }

            JSONArray protocolList = infoObject.getJSONArray("protocalList");
            if (protocolList == null || protocolList.isEmpty()){
                return true;
            }
            List<MerchantThirdProtocolInfo> protocolInfoList = new ArrayList<>();
            for (int i = 0; i < protocolList.size(); i++) {
                JSONObject jsonObject = protocolList.getJSONObject(i);
                String protocolName = jsonObject.getString("protocalName");
                String protocolUrl = jsonObject.getString("protocalUrl");

                MerchantThirdProtocolInfo protocolInfo = new MerchantThirdProtocolInfo();
                protocolInfo.setDateInfo(dateInfo);
                protocolInfo.setInfoId(thirdInfoDTO.getInfoId());
                protocolInfo.setInfoName(thirdInfoDTO.getInfoName());
                protocolInfo.setThirdId(thirdBaseInfo.getId());
                protocolInfo.setThirdName(thirdBaseInfo.getProductName());

                protocolInfo.setProtocolName(protocolName);
                protocolInfo.setProtocolUrl(protocolUrl);

                protocolInfoList.add(protocolInfo);
            }
            if (protocolInfoList.size() > 0){
                boolean saveBatch = merchantThirdProtocolInfoService.saveBatch(protocolInfoList);
                if (!saveBatch) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
            }
            return true;
        } catch (Exception exception) {
            exception.printStackTrace();
            notifyExceptionService.notifyNoticeInfo("MERCHANT_THIRD_SAVE_EXEC", "双授权撞库数据保存", JSON.toJSONString(thirdInfoDTO), exception);
        }
        return false;
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,rollbackFor = Exception.class)
    public boolean updateThirdInfo(ThirdInfoDTO thirdInfoDTO) {
        try {
            MerchantThirdBaseInfo thirdBaseInfo = this.baseMapper.selectEntityByOrderNo(thirdInfoDTO.getOrderNo());
            if (ObjectUtil.isEmpty(thirdBaseInfo)){
                throw new RuntimeException("为空");
            }

            MerchantThirdBaseInfo updateEntity = new MerchantThirdBaseInfo();
            updateEntity.setId(thirdBaseInfo.getId());
            updateEntity.setStatus(thirdInfoDTO.getStatus());
            updateEntity.setRetCode(thirdInfoDTO.getRetCode());
            updateEntity.setRetMsg(thirdInfoDTO.getRetMsg());
            updateEntity.setResultInfo(thirdInfoDTO.getResultInfo());
            return this.updateById(updateEntity);

        } catch (Exception exception) {
            exception.printStackTrace();
            notifyExceptionService.notifyNoticeInfo("MERCHANT_THIRD_UPDATE_EXEC", "双授权撞库数据更新", JSON.toJSONString(thirdInfoDTO), exception);
        }
        return false;
    }


    @Override
    public MerchantThirdBaseInfo selectEntityByOrderNo(String orderNo) {
        return this.baseMapper.selectEntityByOrderNo(orderNo);
    }


}
